package ru.usu.gv.gui.actions;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.graph.Graph;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.uicomponents.UIVertex;
import ru.usu.gv.utils.GraphAlgorithmHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author spupyrev
 * 02.11.2008
 * 
 * Leaves only largest component in graph
 */
public class SimplifyGraphAction extends ActionBase
{
	public SimplifyGraphAction()
	{
	}

	@Override
	public void execute()
	{
		UIGraph uiGraph = GraphCanvas.getInstance().getCurrentGraph();
		Graph graph = uiGraph.getGraph();

		int maxSize = 0, maxIndex = 0;
		int n = graph.getSize();
		int color[] = new int[n];
		Arrays.fill(color, -1);
		int colorIndex = 0;
		for (int i = 0; i < n; i++)
			if (color[i] == -1)
			{
				int[] dist = GraphAlgorithmHelper.bfs(graph, i);
				int tecSize = 0;
				for (int j = 0; j < n; j++)
					if (dist[j] != -1)
					{
						color[j] = colorIndex;
						tecSize++;
					}

				if (tecSize > maxSize)
				{
					maxSize = tecSize;
					maxIndex = colorIndex;
				}

				colorIndex++;
			}

		List<UIVertex> vertexToDelete = new ArrayList<UIVertex>();
		for (int i = 0; i < n; i++)
			if (color[i] != maxIndex)
			{
				vertexToDelete.add(uiGraph.getVertex(i));
			}

		System.out.print("Deleting " + vertexToDelete.size() + " vertexes...");
		for (UIVertex v : vertexToDelete)
			v.delete();
		System.out.println("done");
	}

}
